<template>
    <GetanModal @register="register" @on-ok="handleSubmit">
        <n-form ref="formRef" :model="formValue" label-placement="left" :style="{ marginTop: '20px' }">
            <n-form-item label="角色编码" path="code">
                <n-input v-model:value="formValue.code" placeholder="系统唯一" :disabled="status === 'UPDATE'" />
            </n-form-item>
            <n-form-item label="角色名称" path="name">
                <n-input v-model:value="formValue.name" />
            </n-form-item>
        </n-form>
    </GetanModal>
</template>

<script setup lang="ts">
import { useGetanModal, GetanModal } from "@/components/Modal"
import { api } from "../../api"
import { FormInst } from "naive-ui"

const formRef = ref<FormInst | null>(null)

const formValue = ref<Recordable>({})

const status = ref<string>("")

const { register, methods } = useGetanModal({ title: "新增角色" })

const openAddForm = (defaultData?: Recordable) => {
    formValue.value = defaultData ? { ...defaultData } : {}
    status.value = "ADD"
    methods.open("新增角色")
}

const openUpdateForm = (rowData: Recordable) => {
    formValue.value = { ...rowData }
    status.value = "UPDATE"
    methods.open("修改角色")
}

const emits = defineEmits(["after-add", "after-update", "after"])

defineExpose({ openAddForm, openUpdateForm })

const handleSubmit = () => {
    formRef.value?.validate(async errors => {
        if (!errors) {
            if (status.value === "ADD") {
                const { isOk } = await api.add(formValue.value)
                if (isOk()) {
                    emits("after-add", status.value)
                    emits("after", status.value)
                    methods.close()
                }
            } else {
                const { isOk } = await api.update(formValue.value)
                if (isOk()) {
                    emits("after-update", status.value)
                    emits("after", status.value)
                    methods.close()
                }
            }
        } else {
            console.log(errors)
        }
    })
}
</script>
